<template>
  <div>
    <a-row>
      <a-col
        class="check-item"
        :span="8"
      >
        <a-button type="primary" @click="onAdd" > <a-icon type="file-add" />添加 </a-button>
        <!-- <a-button
          type="primary"
          @click="start"
          :disabled="!hasSelected"
          :loading="loading"
        > 批量操作 </a-button> -->
        <template v-if="hasSelected">
          {{`已选项： ${selectedRowKeys.length} 个`}}
        </template>
      </a-col>
      <a-col
        :span="8"
        :offset="8"
      >
        <!-- <a-form layout="inline">
          <a-form-item>
            <a-row :gutter="12">
              <a-col :span="20">
                <a-input
                  v-decorator="[
                    'captcha',
                    {rules: [{ required: true, message: 'Please input the captcha you got!' }]}
                  ]"
                />
              </a-col>
              <a-col :span="4">
                <a-button type="primary">搜索</a-button>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form> -->
      </a-col>
    </a-row>
    <br />
    <a-table
      bordered
      :dataSource="dataList"
      :columns="columns"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      :pagination='pagination'
    >
      <template
        slot="name"
        slot-scope="text, record"
      >
      </template>
      <template
        slot="operation"
        slot-scope="text, record"
      >
        <a-button-group >
          <a-button type="primary"  @click="onAdd(record.id)">
            <a-icon type="edit"/>编辑</a-button>
          <a-button type="danger" @click="onDelete(record.id)">
            <a-icon type="delete" />删除</a-button>
        </a-button-group>
      </template>
    </a-table>
    <!-- 添加商家抽屉 -->
    <a-drawer
      title="新商家入驻"
      :width="720"
      @close="onClose"
      :visible="visible"
      :wrapStyle="{height: 'calc(100% - 108px)',overflow: 'auto',paddingBottom: '108px'}"
    >
      <a-form :form="form" name='addCom' @submit="handleSubmit" >
        <a-row>
          <a-col :span="24">
            <a-form-item label="商家名称">
              <a-input
                v-decorator="['name', {
                  rules: [{ required: true, message: '商家名称不能为空' }]
                }]"
                placeholder="请输入商家名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="联系人">
              <a-input
                v-decorator="['linkman', {
                  rules: [{ required: true, message: '联系人不能为空' }]
                }]"
                placeholder="请输入联系人姓名"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="联系电话">
              <a-input
                v-decorator="['phone', {
                  rules: [{ required: true, message: 'Please enter user name' }]
                }]"
                placeholder="请输入联系电话"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="微信号">
              <a-input
                v-decorator="['wechat', {
                  rules: [{ required: true, message: 'Please enter user name' }]
                }]"
                placeholder="请输入联系人微信号"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="商家介绍">
              <a-textarea
                v-decorator="['remark', {
                  rules: [{ required: true, message: 'Please enter url description' }]
                }]"
                :rows="4"
                placeholder="请输入商家描述"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <div
          :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }"
        >
          <a-button
            :style="{marginRight: '8px'}"
            @click="onClose"
          >
            取消
          </a-button>
          <a-button html-type="submit" type="primary">保存</a-button>
        </div>
      </a-form>
    </a-drawer>
  </div>
</template>
<script>
import { Modal } from 'ant-design-vue'
import { Message } from 'ant-design-vue'
// 表头
const columns = [
  {
    title: "序号",
    dataIndex: "id"
  },
  {
    title: "商家名称",
    dataIndex: "name"
  },
  {
    title: "联系人",
    dataIndex: "linkman"
  },
  {
    title: "联系方式",
    dataIndex: "phone"
  },
  {
    title: "微信号",
    dataIndex: "wechat"
  },
  {
    title: "介绍",
    dataIndex: "remark"
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" }
  }
];
export default {
  data() {
    return {
      edit:false,
      dataList: [],
      dataCom:{},//某个商家信息
      form: this.$form.createForm(this),
      visible:false,
      columns,
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      pagination:{}
    };
  },
  mounted() {
    let vo = this;
    vo.pagination = {
      showSizeChanger : true,
      showQuickJumper: true,
      pageSize: 10,
      current: 1,
      onChange(current) {
        vo.pagination.current = current;
        vo.initData();
      },
      onShowSizeChange(current, pageSize){
        vo.pagination.current = current;
        vo.pagination.pageSize = pageSize;
        vo.initData();
      }
    };
    vo.initData();
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    }
  },
  methods: {
    onClose() {
      this.visible = false
    },
    onEdit(){
      
    },
    /**
     * @function [onAdd] 编辑与添加商家功能
     * @param [id] 不传递id为添加功能，传递id为编辑功能
     *             传值类型为选择的商家id 
     * */
    onAdd(id){
      let vo = this;
      vo.visible = true;
      if(typeof arguments[0]=='number'){//编辑
        vo.edit = true;
        const dataUrl = `backstage/selOne.do?id=${id}`;
        vo.ajax.get(dataUrl).then((res)=>{
          vo.dataCom = res
        })
      }else{//添加
        vo.edit = false;
      }
    },
    handleSubmit(e){
      e.preventDefault();
      this.form.validateFields((err, fieldsValue) => {
        if (!err) {
          let vo = this,params={},dataUrl='';
          if(vo.edit){
            dataUrl = `backstage/updateCompany.do`;
            params = Object.assign(fieldsValue,{id:vo.dataCom.id});
          }else{
            dataUrl = `backstage/addCompany.do`;
            params = Object.assign(fieldsValue);
          }
          vo.ajax.post(dataUrl,params).then((res)=>{
            if(res==1){//添加成功
              vo.visible = false;
              Message.success('商家入驻成功');
              vo.initData();
            }else{
              Message.error('商家入驻失败');
            }
          })
        }
      });
    },
    // 删除商家
    onDelete(key) {
      let vo = this;
      Modal.confirm({
        title: '确定要删除该商家吗？',
        content: '商家删除后无法恢复',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const dataUrl = `backstage/deleteCompany.do?id=${key}`;
          vo.ajax.get(dataUrl).then(res => {
            if(res == 1){//删除成功
              Message.success('删除成功');
              vo.initData();
            }else if(res==0){
              Message.error('删除失败');
            }
          });
        },
        onCancel() {
          Message.warning('取消删除');
        },
      });
    },
    start() {
      this.loading = true;
      // ajax request after empty completing
      setTimeout(() => {
        this.loading = false;
        this.selectedRowKeys = [];
      }, 1000);
    },
    //全选
    onSelectChange(selectedRowKeys) {
      console.log("已选项: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    initData(){
      let vo = this;
      const dataUrl =`backstage/selAllCompany.do?nowPage=${vo.pagination.current}&pageSize=${vo.pagination.pageSize}`;
      vo.ajax.get(dataUrl).then(res => {
        let arr = res.data.map((v,i)=>{
          v.key = i;
          return v;
        })
        vo.dataList = arr;
        console.log(arr);
        vo.pagination = {
          ...vo.pagination,
          total: res.totalCount,
          showTotal: () => `共${res.totalCount}个商家`
        };
      });
    }
  },
  watch:{
    dataCom (o) {
      this.form.setFieldsValue({
        name: o.name,
        linkman: o.linkman,
        phone: o.phone,
        wechat: o.wechat,
        remark: o.remark
      });
    }
  }
  
};
</script>
<style>
.check-item {
  text-align: left;
}
</style>
